package io.renren.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.renren.annotation.Login;
import io.renren.constant.AppConstant;
import io.renren.entity.*;
import io.renren.service.CgsBusinessService;
import io.renren.service.PersonalCenterService;
import io.renren.util.HttpClientUtil;
import io.renren.util.UUIDGenerator;
import io.renren.util.XMLMapUtil;
import io.renren.vo.RespModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by ThinkPad on 2018/12/3.
 */
@RestController
@RequestMapping("/cgsBusiness")
@Api(tags = "一网通一次办")
public class CgsBusinessController extends AbstractController {
    @Autowired
    private CgsBusinessService cgsBusinessService;

    @Autowired
    private PersonalCenterService personalCenterService;

    @PostMapping(value = "/getReservations/{bookType}", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "查询预约列表", produces = MediaType.APPLICATION_JSON_VALUE)
    @com.cxytiandi.encrypt.springboot.annotation.Decrypt
    @com.cxytiandi.encrypt.springboot.annotation.Encrypt
    public RespModel getReservations(@PathVariable String bookType) {
        if (StringUtils.isEmpty(bookType)) {
            return new RespModel().getRespModelInstance(AppConstant.PARAM_IS_MISS, "缺少业务类型", null);
        }
        List<Map> maps = cgsBusinessService.queryReservations(bookType);
        return new RespModel().getRespModelInstance(AppConstant.STATU_SUCCESS, "", maps);
    }

    @GetMapping(value = "/getCgsInfoList", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "查询车管所列表信息", produces = MediaType.APPLICATION_JSON_VALUE)
//    @com.cxytiandi.encrypt.springboot.annotation.Decrypt
    @com.cxytiandi.encrypt.springboot.annotation.Encrypt
    public RespModel getCgsInfoList() {
        List<Map> maps = cgsBusinessService.queryCgsInfoList("1");
        return new RespModel().getRespModelInstance(AppConstant.STATU_SUCCESS, "", maps);
    }

    @PostMapping(value = "/saveBusinessBookInfo", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "保存预约信息", produces = MediaType.APPLICATION_JSON_VALUE)
    @com.cxytiandi.encrypt.springboot.annotation.Decrypt
    @com.cxytiandi.encrypt.springboot.annotation.Encrypt
    public RespModel saveBusinessBookInfo(@Valid CgsBookInfo cgsBookInfo, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            StringBuffer sb = new StringBuffer();
            bindingResult.getFieldErrors().forEach(fieldError -> sb.append(fieldError.getDefaultMessage()).append(";"));
            return new RespModel().getRespModelInstance(AppConstant.PARAM_IS_MISS, sb.toString(), null);
        }
        //查询用户是否已经预约
        cgsBookInfo.setStatus("2");
        List<Map> maps = cgsBusinessService.queryUserReservations(cgsBookInfo);
        if (CollectionUtils.isEmpty(maps)) {
            cgsBookInfo.setId(UUID.randomUUID().toString());
            cgsBookInfo.setStatus("0");
            cgsBusinessService.saveBusinessBookInfo(cgsBookInfo);
            return new RespModel().getRespModelInstance(AppConstant.STATU_SUCCESS, "", null);
        } else {
            return new RespModel().getRespModelInstance(AppConstant.THINGS_HAVE_BEAN_DONE, "已预约当前业务", maps);
        }
    }

    @PostMapping(value = "/cancelBookInfo/{bookId}", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "取消预约", produces = MediaType.APPLICATION_JSON_VALUE)
    @com.cxytiandi.encrypt.springboot.annotation.Decrypt
    @com.cxytiandi.encrypt.springboot.annotation.Encrypt
    public RespModel cancelBookInfo(@PathVariable String bookId) {
        if (StringUtils.isEmpty(bookId)) {
            return new RespModel<>().getRespModelInstance(AppConstant.PARAM_IS_MISS, "预约标识缺失", null);
        }
        Integer cancel_count = cgsBusinessService.cancelBookInfo(bookId);
        if (cancel_count != null && cancel_count == 1) {
            return new RespModel<>().getRespModelInstance(AppConstant.STATU_SUCCESS, "", null);
        } else {
            return new RespModel<>().getRespModelInstance(AppConstant.STATU_FAIL, "取消预约失败，找不到预约信息", null);
        }
    }

    @PostMapping(value = "/getMyReservations", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "查询预约信息")
    @com.cxytiandi.encrypt.springboot.annotation.Decrypt
    @com.cxytiandi.encrypt.springboot.annotation.Encrypt
    public RespModel queryMyReservations(@Valid CgsBookInfo cgsBookInfo, BindingResult bindingResult) {
        if (bindingResult.getFieldError("userId") != null) {
            return new RespModel().getRespModelInstance(AppConstant.PARAM_IS_MISS,
                    bindingResult.getFieldError("userId").getDefaultMessage(), null);
        }
        List<Map> maps = cgsBusinessService.queryUserReservations(cgsBookInfo);
        return new RespModel().getRespModelInstance(AppConstant.STATU_SUCCESS, "", maps);
    }


    @PostMapping(value = "/queryBookTimeReservations", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "查询指定日期预约各时间段预约数量")
    @com.cxytiandi.encrypt.springboot.annotation.Decrypt
    @com.cxytiandi.encrypt.springboot.annotation.Encrypt
    public RespModel queryBookTimeReservations(@Valid CgsBookInfo cgsBookInfo, BindingResult bindingResult) {
        StringBuilder sb = new StringBuilder();
        if (bindingResult.hasErrors()) {
            bindingResult.getFieldErrors().forEach(fieldError -> {
                if (fieldError.getField().equals("cgsId") || fieldError.getField().equals("bookDate")) {
                    sb.append(fieldError.getDefaultMessage()).append(";");
                }
            });
            if (sb.length() > 0) {
                return new RespModel().getRespModelInstance(AppConstant.PARAM_IS_MISS, sb.toString(), null);
            }
        }

        List<Map> maps = cgsBusinessService.queryBookTimeReservations(cgsBookInfo);
        return new RespModel().getRespModelInstance(AppConstant.STATU_SUCCESS, "", maps);
    }

    @PostMapping(value = "/setArrival", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "更新用户到达状态")
    @com.cxytiandi.encrypt.springboot.annotation.Decrypt
    @com.cxytiandi.encrypt.springboot.annotation.Encrypt
    public RespModel setArrival(@Valid CgsBookInfo cgsBookInfo, BindingResult bindingResult, String bookId) {
        List<String> check_field = Arrays.asList("id", "userId");
        List<String> messageList = customizeCheckFieldAdapter(check_field, bindingResult);
        if (StringUtils.isEmpty(bookId)) {
            messageList.add("缺失预约标识");
        }
        if (messageList.size() > 0) {
            return new RespModel().getRespModelInstance(AppConstant.PARAM_IS_MISS, StringUtils.join(messageList, ","), null);
        }

        cgsBookInfo.setId(bookId);
        Integer update_count = cgsBusinessService.updateBookInfoArrival(cgsBookInfo);
        if (update_count == null || update_count == 0) {
            return new RespModel().getRespModelInstance(AppConstant.STATU_FAIL, "更新失败，请检查参数是否正确", null);
        } else {
            return new RespModel().getRespModelInstance(AppConstant.STATU_SUCCESS, "", null);
        }
    }

    @GetMapping(value = "/getBusinessDetail", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "查询业务明细", produces = MediaType.APPLICATION_JSON_VALUE)
//    @com.cxytiandi.encrypt.springboot.annotation.Decrypt
    @com.cxytiandi.encrypt.springboot.annotation.Encrypt
    public RespModel getBusinessDetail(String businessId) {
        if (StringUtils.isEmpty(businessId)) {
            return new RespModel().getRespModelInstance(AppConstant.PARAM_IS_MISS, "缺失业务标识", null);
        }
        Map paramMap = new HashMap() {{
            put("businessId", businessId);
            put("type", "1");
        }};
        List<Map> flowList = cgsBusinessService.queryBusinessDetail(paramMap);
        paramMap.put("type", "2");
        List<Map> materialList = cgsBusinessService.queryBusinessDetail(paramMap);
        Map result_map = new HashMap() {{
            put("flowList", flowList);
            put("materialList", materialList);
        }};

        return new RespModel().getRespModelInstance(AppConstant.STATU_SUCCESS, "", result_map);
    }

    @Login
    @PostMapping(value = "/submitPostInfo/{applicationId}", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "提交警邮办申请", produces = MediaType.APPLICATION_JSON_VALUE)
    @com.cxytiandi.encrypt.springboot.annotation.Decrypt
    @com.cxytiandi.encrypt.springboot.annotation.Encrypt
    public RespModel submitPostInfo(@Valid CgsPolicePost cgsPolicePost, BindingResult bindingResult, HttpServletRequest request) {
        List<String> strings = customizeCheckFieldAdapter(bindingResult);
        if (strings.size() > 0) {
            return new RespModel().getRespModelInstance(AppConstant.PARAM_IS_MISS,
                    StringUtils.join(strings, ","), null);
        }
        String userId = (String) request.getAttribute("username");

        //查询是否已经提交申请
        List<CgsPolicePost> cgsPolicePosts = cgsBusinessService.queryMyPolicePostInfo(userId);
        List<CgsPolicePost> collect = cgsPolicePosts.stream()
                .filter(cgsPolicePost1 -> {
                    if(cgsPolicePost1.getBusinessId().equals(cgsPolicePost.getBusinessId())) {
                       return "2".equals(cgsPolicePost1.getStatus()) || "0".equals(cgsPolicePost1.getStatus());
                    }else{
                        return false;
                    }
                })
                .collect(Collectors.toList());
        if (collect.size() != 0) {
            return new RespModel().getRespModelInstance(AppConstant.THINGS_HAVE_BEAN_DONE, "有未办结的申请，无法提交新的申请", null);
        }
        //查询用户vip数据获取身份证信息等
        Map map = personalCenterService.queryAppUserInfo(userId);
        if (CollectionUtils.isEmpty(map)) {
            return new RespModel().getRespModelInstance(AppConstant.CONDITION_NOT_SATISFIED, "请先升级为VIP用户再办理该业务", null);
        }
        cgsPolicePost.setUserName(((String) map.get("real_name")));
        cgsPolicePost.setScanUrlf(((String) map.get("scan_url_f")));
        cgsPolicePost.setScanUrlz(((String) map.get("scan_url_z")));
        cgsPolicePost.setIdCardNum(((String) map.get("sfzh")));
        cgsPolicePost.setApplyUserId(userId);
        cgsPolicePost.setVehicleNum(((String) map.get("cphm")));
        if (StringUtils.isNotEmpty(cgsPolicePost.getTravelLicense())) {
            String travelLicense = uploadBase64StrImage(cgsPolicePost.getTravelLicense(), userId + "-travelLicense.png");
            cgsPolicePost.setTravelLicense(travelLicense);
        }
        if (StringUtils.isNotEmpty(cgsPolicePost.getInsurancePolicy())) {
            String insurancePolicy = uploadBase64StrImage(cgsPolicePost.getInsurancePolicy(), userId + "-insurancePolicy.png");
            cgsPolicePost.setInsurancePolicy(insurancePolicy);
        }
        return cgsBusinessService.savePostInfo(cgsPolicePost);
    }

    @PostMapping(value = "/getMyPolicePostInfo/{userId}", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "查询我的警邮办", produces = MediaType.APPLICATION_JSON_VALUE)
    @com.cxytiandi.encrypt.springboot.annotation.Decrypt
    @com.cxytiandi.encrypt.springboot.annotation.Encrypt
    public RespModel queryMyPolicePostInfo(@PathVariable String userId) {
        if (StringUtils.isEmpty(userId)) {
            return new RespModel().getRespModelInstance(AppConstant.PARAM_IS_MISS, "缺失用户标识", null);
        }
        List<CgsPolicePost> cgsPolicePosts = cgsBusinessService.queryMyPolicePostInfo(userId);
        return new RespModel().getRespModelInstance(AppConstant.STATU_SUCCESS, "", cgsPolicePosts);
    }
    @Login
    @PostMapping(value = "/submitReConsiderInfo/{applicationId}", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "提交复议申请")
    @com.cxytiandi.encrypt.springboot.annotation.Decrypt
    @com.cxytiandi.encrypt.springboot.annotation.Encrypt
    public RespModel submitReConsiderInfo(HttpServletRequest request, @Valid CgsReconsider cgsReconsider, BindingResult bindingResult) {
        List<String> strings = customizeCheckFieldAdapter(bindingResult);
        if (!CollectionUtils.isEmpty(strings)) {
            return new RespModel().getRespModelInstance(AppConstant.PARAM_IS_MISS, StringUtils.join(strings, ","), null);
        }
        String userId = (String) request.getAttribute("username");
        //查询VIP用户信息
        Map map = personalCenterService.queryAppUserInfo(userId);
        if (CollectionUtils.isEmpty(map)) {
            return new RespModel().getRespModelInstance(AppConstant.CONDITION_NOT_SATISFIED, "请先升级为VIP", null);
        }
        cgsReconsider.setId(UUID.randomUUID().toString());
        cgsReconsider.setApplyUserId(userId);
        cgsReconsider.setIdCardNum(((String) map.get("sfzh")));
        cgsReconsider.setScanUrlf(((String) map.get("scan_url_f")));
        cgsReconsider.setScanUrlz(((String) map.get("scan_url_z")));
        cgsReconsider.setUserName(((String) map.get("real_name")));
        cgsReconsider.setVehicleNum(((String) map.get("cphm")));
        String trvalLicense = uploadBase64StrImage(cgsReconsider.getTrvalLicense(), userId + "trvalLicense.png");
        cgsReconsider.setTrvalLicense(trvalLicense);
        String materialOne = uploadBase64StrImage(cgsReconsider.getMaterialOne(), userId + "MaterialOne.png");
        cgsReconsider.setMaterialOne(materialOne);
        String materialTwo = uploadBase64StrImage(cgsReconsider.getMaterialTwo(), userId + "MaterialOne.png");
        cgsReconsider.setMaterialTwo(materialTwo);

        Integer insert_count = cgsBusinessService.insertReconsiderInfo(cgsReconsider);
        if (insert_count == null || insert_count != 1) {
            return new RespModel().getRespModelInstance(AppConstant.STATU_FAIL, "提交失败", null);
        }
        return new RespModel().getRespModelInstance(AppConstant.STATU_SUCCESS, "提交成功，工作人员将会在5个工作日内给您答复！", null);
    }

    @PostMapping(value = "/getMyReconsiderList/{userId}", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "获取我的复议列表", produces = MediaType.APPLICATION_JSON_VALUE)
    @com.cxytiandi.encrypt.springboot.annotation.Decrypt
    @com.cxytiandi.encrypt.springboot.annotation.Encrypt
    public RespModel getMyReconsiderList(@PathVariable String userId) {
        List<CgsReconsider> cgsReconsiders = cgsBusinessService.queryMyReconsiderList(userId);
        return new RespModel().getRespModelInstance(AppConstant.STATU_SUCCESS, "", cgsReconsiders);
    }

    @Login
    @PostMapping(value = "/submitPassportInfo/{applicationId}", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "提交通行证申请", produces = MediaType.APPLICATION_JSON_VALUE)
    @com.cxytiandi.encrypt.springboot.annotation.Decrypt
    @com.cxytiandi.encrypt.springboot.annotation.Encrypt
    public RespModel submitPassportInfo(HttpServletRequest request,
                                       @RequestBody CgsPassportApply cgsPassportApply,
                                        BindingResult bindingResult) {
        List<String> strings = customizeCheckFieldAdapter(bindingResult);
        String userId = (String) request.getAttribute("username");
        if (!CollectionUtils.isEmpty(strings)) {
            return new RespModel().getRespModelInstance(AppConstant.PARAM_IS_MISS,
                    StringUtils.join(strings, ","), null);
        }
        //设置通行证序号
        String XH = getXH(cgsBusinessService.getSequenceNumber());
        cgsPassportApply.setXH(XH);
        String travelLicense = uploadBase64StrImage(cgsPassportApply.getTravelLicense(), userId + "travelLicense.png");
        cgsPassportApply.setTravelLicense(travelLicense);
        String drivingLicense = uploadBase64StrImage(cgsPassportApply.getDrivingLicense(), userId + "-drivingLicense.png");
        cgsPassportApply.setDrivingLicense(drivingLicense);
        String GoodsscortCard = uploadBase64StrImage(cgsPassportApply.getGoodsscortCard(), userId + "-GoodsscortCard.png");
        cgsPassportApply.setGoodsscortCard(GoodsscortCard);
        String businessLicense = uploadBase64StrImage(cgsPassportApply.getBusinessLicense(), userId + "-businessLicense.png");
        cgsPassportApply.setBusinessLicense(businessLicense);
        String qualificationProof = uploadBase64StrImage(cgsPassportApply.getQualificationProof(), userId + "-qualificationProof.png");
        cgsPassportApply.setQualificationProof(qualificationProof);
        String illegalDealProve = uploadBase64StrImage(cgsPassportApply.getIllegalDealProve(), userId + "-illegalDealProve.png");
        cgsPassportApply.setIllegalDealProve(illegalDealProve);
        String trainingCertificate = uploadBase64StrImage(cgsPassportApply.getTrainingCertificate(), userId + "-trainingCertificate.png");
        cgsPassportApply.setTrainingCertificate(trainingCertificate);
        String passportApplication = uploadBase64StrImage(cgsPassportApply.getPassportApplication(), userId + "-passportApplication.png");
        cgsPassportApply.setPassportApplication(passportApplication);
        cgsPassportApply.setStatus("0");
        cgsPassportApply.setId(UUID.randomUUID().toString());
        cgsPassportApply.setApplyUserId(userId);
        //这个是通行证类型，需要从app端传过来
//        cgsPassportApply.setTXZLX("03");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        String date = sdf.format(new Date());
        cgsPassportApply.setCreateTime(date);
        List<Map<String, Object>> maps = cgsBusinessService.queryPassportTypeList2(cgsPassportApply.getPassportId());
        for (Map map : maps){
            cgsPassportApply.setTXZLX((String) map.get("TXQYLX"));
            cgsPassportApply.setPassportName((String) map.get("TXZMC"));
        }
        //通行证存入集成平台
        Integer insert_count1 = cgsBusinessService.insertPassportApplyToOracle(cgsPassportApply);
        if (insert_count1 == null || insert_count1 != 1){
            return new RespModel().getRespModelInstance(AppConstant.STATU_FAIL, "集成平台同步失败", null);
        }
        //通行证存入管理后台
        Integer insert_count = cgsBusinessService.insertPassportApply(cgsPassportApply);
        if (insert_count == null || insert_count != 1) {
            return new RespModel().getRespModelInstance(AppConstant.STATU_FAIL, "后台系统同步失败", null);
        }


        return new RespModel().getRespModelInstance(AppConstant.STATU_SUCCESS, "", null);
    }

    public static String getXH(Integer sequenceNumber){
        String XH = "3704";
        if (sequenceNumber<10){
            XH = XH+"00000000000"+ sequenceNumber.toString();
            return XH;
        }
        if (sequenceNumber<100){
            XH = XH+"0000000000"+ sequenceNumber.toString();
            return XH;
        }
        if (sequenceNumber<1000){
            XH = XH+"000000000"+ sequenceNumber.toString();
            return XH;
        }
        if (sequenceNumber<10000){
            XH = XH+"00000000"+ sequenceNumber.toString();
            return XH;
        }
        if (sequenceNumber<100000){
            XH = XH+"0000000"+ sequenceNumber.toString();
            return XH;
        }
        if (sequenceNumber<1000000){
            XH = XH+"000000"+ sequenceNumber.toString();
            return XH;
        }
        if (sequenceNumber<10000000){
            XH = XH+"00000"+ sequenceNumber.toString();
            return XH;
        }
        if (sequenceNumber<100000000){
            XH = XH+"0000"+ sequenceNumber.toString();
            return XH;
        }
        return XH;
    }

    @GetMapping(value = "/getPassportList/{userId}", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "查询通行证列表", produces = MediaType.APPLICATION_JSON_VALUE)
//    @com.cxytiandi.encrypt.springboot.annotation.Decrypt
    @com.cxytiandi.encrypt.springboot.annotation.Encrypt
    public RespModel getPassportList(@PathVariable String userId) {
        if (StringUtils.isEmpty(userId)) {
            return new RespModel().getRespModelInstance(AppConstant.PARAM_IS_MISS, "缺少用户标识", null);
        }
        //获取本地通行证列表
        List<CgsPassportApply> cgsPassportApplieListByMysql = cgsBusinessService.queryMyPassportApply(userId);
        //设置序号集合
        List<String> xhList = new ArrayList<>();
        for(CgsPassportApply cgsPassportApply : cgsPassportApplieListByMysql){
            if(cgsPassportApply.getXH() != null && !"".equals(cgsPassportApply.getXH())){
                xhList.add(cgsPassportApply.getXH());
            }
        }
        //查询集成平台通行证列表
        List<CgsPassportApply> cgsPassportApplieListByOracle = cgsBusinessService.queryMyPassportApplyByOracle(xhList);
        for (CgsPassportApply cgsPassportApplie:cgsPassportApplieListByOracle){
            for (CgsPassportApply cgsPassportApplie1:cgsPassportApplieListByMysql){
                if (cgsPassportApplie.getXH().equals(cgsPassportApplie1.getXH())){
                    if (!cgsPassportApplie.getStatus().equals(cgsPassportApplie1.getStatus())){
                        cgsPassportApplie1.setStatus(cgsPassportApplie.getStatus());
                        cgsPassportApplie1.setStatusExplain(cgsPassportApplie.getStatusExplain());
                        cgsBusinessService.updateStatus(cgsPassportApplie1);
                    }
                }
            }
        }
        //状态同步完成后再次查询通行证列表数据回显到APP
        List<CgsPassportApply> cgsPassportApplies = cgsBusinessService.queryMyPassportApply(userId);
        return new RespModel().getRespModelInstance(AppConstant.STATU_SUCCESS, "", cgsPassportApplies);
    }

    @GetMapping(value = "/getEprBusCheckCgs", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "查询新能源查验车管所", produces = MediaType.APPLICATION_JSON_VALUE)
//    @com.cxytiandi.encrypt.springboot.annotation.Decrypt
    @com.cxytiandi.encrypt.springboot.annotation.Encrypt
    public RespModel getEprBusCheckCgs() {
        HashMap hashMap = new HashMap() {{
            put("id", "2");
            put("name", "市车管所二分所");
        }};

        HashMap hashMap1 = new HashMap() {{
            put("id", "3");
            put("name", "市车管所三分所");
        }};
        return new RespModel().getRespModelInstance(AppConstant.STATU_SUCCESS, "", Arrays.asList(hashMap, hashMap1));
    }
    @Login
    @PostMapping(value = "/submitEprBusCheckInfo/{applicationId}", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "提交新能源公交车车辆查验申请")
    @com.cxytiandi.encrypt.springboot.annotation.Decrypt
    @com.cxytiandi.encrypt.springboot.annotation.Encrypt
    public RespModel submitEprBusCheckInfo(HttpServletRequest request,
                                           @Valid CgsEprBusCheck cgsEprBusCheck,
                                           BindingResult bindingResult) {
        List<String> strings = customizeCheckFieldAdapter(bindingResult);
        if (!CollectionUtils.isEmpty(strings)) {
            return new RespModel<>().getRespModelInstance(AppConstant.PARAM_IS_MISS, StringUtils.join(strings, ","), null);
        }
        String userId = ((String) request.getAttribute("userId"));
        String s = uploadBase64StrImage(cgsEprBusCheck.getApplyFile(), userId + "-EprBusCheckApply.png");
        cgsEprBusCheck.setApplyFile(s);
        cgsEprBusCheck.setId(UUID.randomUUID().toString());
        cgsEprBusCheck.setApplyUserId(userId);
        Integer insert_count = cgsBusinessService.insertCgsEprInfoBusCheck(cgsEprBusCheck);
        if (insert_count == null || insert_count != 1) {
            return new RespModel().getRespModelInstance(AppConstant.STATU_FAIL, "提交失败", null);
        }
        return new RespModel().getRespModelInstance(AppConstant.STATU_SUCCESS, "申请提交成功", null);
    }

    @GetMapping(value = "/getMyCgsEprInfoBusCheckList/{userId}", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "查询新能源汽车申请列表", produces = MediaType.APPLICATION_JSON_VALUE)
//    @com.cxytiandi.encrypt.springboot.annotation.Decrypt
    @com.cxytiandi.encrypt.springboot.annotation.Encrypt
    public RespModel queryMyCgsEprInfoBusCheckList(@PathVariable String userId) {
        if (StringUtils.isEmpty(userId)) {
            return new RespModel().getRespModelInstance(AppConstant.PARAM_IS_MISS, "用户标识缺失", null);
        }
        List<CgsEprBusCheck> cgsEprBusChecks = cgsBusinessService.queryMyCgsEprInfoBusCheckList(userId);
        return new RespModel().getRespModelInstance(AppConstant.STATU_SUCCESS, "", cgsEprBusChecks);
    }

    @GetMapping(value = "/getCgsBusinessTopicList/{businessType}", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "查询车管所导办信息列表", produces = MediaType.APPLICATION_JSON_VALUE)
//    @com.cxytiandi.encrypt.springboot.annotation.Decrypt
    @com.cxytiandi.encrypt.springboot.annotation.Encrypt
    public RespModel queryCgsBusinessTopicList(@PathVariable String businessType) {
        if (StringUtils.isEmpty(businessType)) {
            return new RespModel().getRespModelInstance(AppConstant.PARAM_IS_MISS, "缺少业务类型", null);
        }
        List<Map> maps = cgsBusinessService.queryCgsBusinessTopicList(businessType);
        return new RespModel().getRespModelInstance(AppConstant.STATU_SUCCESS, "", maps);
    }

    @GetMapping(value = "/getCgsBusinessTopicDetail/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "查询业务导办详情", produces = MediaType.APPLICATION_JSON_VALUE)
//    @com.cxytiandi.encrypt.springboot.annotation.Decrypt
    @com.cxytiandi.encrypt.springboot.annotation.Encrypt
    public RespModel queryCgsBusinessTopicDetail(@PathVariable String id) {
        if (StringUtils.isEmpty(id)) {
            return new RespModel<>().getRespModelInstance(AppConstant.STATU_FAIL, "缺失业务标识", null);
        }

        List<Map> maps = cgsBusinessService.queryCgsBusinessTopicDetail(id);
        return new RespModel().getRespModelInstance(AppConstant.STATU_SUCCESS, "", maps);
    }

    @GetMapping(value = "/getCgsBusinessTopicDetailByBusinessId/{businessId}", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "查询业务导办详情", produces = MediaType.APPLICATION_JSON_VALUE)
//    @com.cxytiandi.encrypt.springboot.annotation.Decrypt
    @com.cxytiandi.encrypt.springboot.annotation.Encrypt
    public RespModel getCgsBusinessTopicDetailByBusinessId(@PathVariable String businessId) {
        if (StringUtils.isEmpty(businessId)) {
            return new RespModel<>().getRespModelInstance(AppConstant.STATU_FAIL, "缺失业务标识", null);
        }

        List<Map> maps = cgsBusinessService.queryCgsBusinessTopicDetailByBusinessId(businessId);
        return new RespModel().getRespModelInstance(AppConstant.STATU_SUCCESS, "", maps);
    }

    @GetMapping(value = "/getPassportInitData", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "获取通行证相关信息", produces = MediaType.APPLICATION_JSON_VALUE)
//    @com.cxytiandi.encrypt.springboot.annotation.Decrypt
    @com.cxytiandi.encrypt.springboot.annotation.Encrypt
    public RespModel getPassportInitData(@RequestParam Map<String, Object> params) {
    /*public RespModel getPassportInitData() {
        //获取通行证类型
        List<Map> passportTypeList = cgsBusinessService.queryPassportTypeList();
        //获取运输货物名称
        List<Map> goods_name = cgsBusinessService.getDictValuesList("goods_name");
        //获取线路名称
        List<Map> line_number = cgsBusinessService.getDictValuesList("line_name");
        //车辆类型
        List<Map> hpzl = cgsBusinessService.getDictValuesList("hpzl");
        //审核大队
        List<Map> passport_verify = cgsBusinessService.getDictValuesList("passport_verify");
        HashMap hashMap = new HashMap() {{
            put("passportList", passportTypeList);
            put("goodsNameList", goods_name);
            put("lineNameList", line_number);
            put("vehicleTypeList", ShootVehicleMapperhpzl);
            put("passportVerify", passport_verify);
        }};
        return new RespModel().getRespModelInstance(AppConstant.STATU_SUCCESS, "", hashMap);*/
        String auditDept = (String)params.get("auditDept");
        //获取通行证类型
        List<Map<String, Object>> passportTypeList = cgsBusinessService.queryPassportTypeList1(auditDept);
        //获取运输货物名称
        List<Map> goods_name = cgsBusinessService.getDictValuesList("goods_name");
        //获取线路名称
        List<RoadMsgEntity> line_number = cgsBusinessService.queryRoadMsgInfo(auditDept);
        //车辆类型
        List<Map> hpzl = cgsBusinessService.getDictValuesList("hpzl");
        //规定区域
        List<RuleAreaEntity> ruleAreaList = cgsBusinessService.queryRuleArea(auditDept);
        //规定路线
        List<RuleLineEntity> ruleLineList = cgsBusinessService.queryRuleLine(auditDept);
        HashMap hashMap = new HashMap() {{
            put("passportList", passportTypeList);
            put("goodsNameList", goods_name);
            put("lineNameList", line_number);
            put("vehicleTypeList", hpzl);
            put("ruleAreaList", ruleAreaList);
            put("ruleLineList", ruleLineList);
        }};
        return new RespModel().getRespModelInstance(AppConstant.STATU_SUCCESS, "", hashMap);
    }

    @GetMapping(value = "/getIllegalAddressList", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "查询违法地点", produces = MediaType.APPLICATION_JSON_VALUE)
//    @com.cxytiandi.encrypt.springboot.annotation.Decrypt
    @com.cxytiandi.encrypt.springboot.annotation.Encrypt
    public RespModel getIllegalAddressList() {
        List<Map> maps = cgsBusinessService.queryCgsInfoList("2");
        return new RespModel().getRespModelInstance(AppConstant.STATU_SUCCESS, "", maps);
    }

    @GetMapping(value = "/getReconsiderReason", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "查询复议纠错下拉框数据")
//    @com.cxytiandi.encrypt.springboot.annotation.Decrypt
    @com.cxytiandi.encrypt.springboot.annotation.Encrypt
    public RespModel getReconsiderReason(String type) {
        if (StringUtils.isEmpty(type)) {
            return new RespModel().getRespModelInstance(AppConstant.PARAM_IS_MISS, "缺失类型信息", null);
        }
        String key = "";
        if ("01".equals(type)) {
            key = "highSpeedReconsider";
        } else if ("02".equals(type)) {
            key = "cityRoadRecosider";
        }
        List<Map> dictValuesList = cgsBusinessService.getDictValuesList(key);
        return new RespModel().getRespModelInstance(AppConstant.STATU_SUCCESS, "", dictValuesList);
    }
    @Login
    @PostMapping(value = "/submitAccidentCheck/{applicationId}", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "提交道路交通事故复核申请", produces = MediaType.APPLICATION_JSON_VALUE)
    @com.cxytiandi.encrypt.springboot.annotation.Decrypt
    @com.cxytiandi.encrypt.springboot.annotation.Encrypt
    public RespModel submitAccidentCheck(@Valid CgsAccidentCheck cgsAccidentCheck, BindingResult bindingResult, HttpServletRequest request) {
        List<String> strings = customizeCheckFieldAdapter(bindingResult);
        if (!CollectionUtils.isEmpty(strings)) {
            return new RespModel().getRespModelInstance(AppConstant.PARAM_IS_MISS, StringUtils.join(strings, ","), null);
        }
        String userId = ((String) request.getAttribute("username"));
        Map map = personalCenterService.queryAppUserInfo(userId);
        if (CollectionUtils.isEmpty(map)) {
            return new RespModel().getRespModelInstance(AppConstant.CONDITION_NOT_SATISFIED, "请先升级为VIP", null);
        }

        cgsAccidentCheck.setApplyUserId(userId);
        cgsAccidentCheck.setUserName(((String) map.get("real_name")));
        cgsAccidentCheck.setIdCardNum(((String) map.get("sfzh")));
        cgsAccidentCheck.setScanUrlZ(((String) map.get("scan_url_z")));
        cgsAccidentCheck.setScanUrlF(((String) map.get("scan_url_f")));

        String accidentCheckFile1 = uploadBase64StrImage(cgsAccidentCheck.getAccidentCheckFile1(), userId + "-accidentCheckFile1.png");
        cgsAccidentCheck.setAccidentCheckFile1(accidentCheckFile1);
        String accidentCheckFile2 = uploadBase64StrImage(cgsAccidentCheck.getAccidentCheckFile2(), userId + "-accidentCheckFile2.png");
        cgsAccidentCheck.setAccidentCheckFile2(accidentCheckFile2);
        String accidentCheckFile3 = uploadBase64StrImage(cgsAccidentCheck.getAccidentCheckFile3(), userId + "-accidentCheckFile3.png");
        cgsAccidentCheck.setAccidentCheckFile3(accidentCheckFile3);

        String accidentFile1 = uploadBase64StrImage(cgsAccidentCheck.getAccidentFile1(), userId + "-accidentFile1.png");
        cgsAccidentCheck.setAccidentFile1(accidentFile1);
        String accidentFile2 = uploadBase64StrImage(cgsAccidentCheck.getAccidentFile2(), userId + "-accidentFile2.png");
        cgsAccidentCheck.setAccidentFile2(accidentFile2);
        String accidentFile3 = uploadBase64StrImage(cgsAccidentCheck.getAccidentFile3(), userId + "-accidentFile3.png");
        cgsAccidentCheck.setAccidentFile3(accidentFile3);

        cgsAccidentCheck.setId(UUID.randomUUID().toString());
        Integer insert_count = cgsBusinessService.insertAccidentCheck(cgsAccidentCheck);
        if (insert_count == null || insert_count != 1) {
            return new RespModel().getRespModelInstance(AppConstant.STATU_FAIL, "提交失败", null);
        }
        return new RespModel().getRespModelInstance(AppConstant.STATU_SUCCESS, "提交成功", null);
    }

    @GetMapping(value = "/getAccidentCheckList/{userId}", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "查询我的事故复核申请列表", produces = MediaType.APPLICATION_JSON_VALUE)
//    @com.cxytiandi.encrypt.springboot.annotation.Decrypt
    @com.cxytiandi.encrypt.springboot.annotation.Encrypt
    public RespModel getAccidentCheckList(@PathVariable String userId) {
        if (StringUtils.isEmpty(userId)) {
            return new RespModel().getRespModelInstance(AppConstant.PARAM_IS_MISS, "缺失用户标识", null);
        }
        List<CgsAccidentCheck> cgsAccidentChecks = cgsBusinessService.queryAccidentCheckList(userId);
        return new RespModel().getRespModelInstance(AppConstant.STATU_SUCCESS, "", cgsAccidentChecks);
    }

    @GetMapping(value = "/getPolicePostFee", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "查询警邮办相关费用", produces = MediaType.APPLICATION_JSON_VALUE)
//    @com.cxytiandi.encrypt.springboot.annotation.Decrypt
    @com.cxytiandi.encrypt.springboot.annotation.Encrypt
    public RespModel getPolicePostFee(String businessId) {
        if (StringUtils.isEmpty(businessId)) {
            return new RespModel().getRespModelInstance(AppConstant.PARAM_IS_MISS, "缺失业务类型标识", null);
        }
        //工本费
        List<Map> maps = cgsBusinessService.queryPolicePostFee(new HashMap() {{
            put("feeType", "1");
            put("businessId", businessId);
        }});
//        邮寄费
        List<Map> maps1 = cgsBusinessService.queryPolicePostFee(new HashMap() {{
            put("feeType", "2");
            put("businessId", businessId);
        }});
        return new RespModel().getRespModelInstance(AppConstant.STATU_SUCCESS, "",
                new HashMap() {{
                    put("nominalFee", maps);
                    put("postFee", maps1);
                }});
    }

    /**
     * 获取预支付订单号
     */
    @PostMapping(value = "/getPrePayId", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "获取预支付订单号")
    @com.cxytiandi.encrypt.springboot.annotation.Decrypt
    @com.cxytiandi.encrypt.springboot.annotation.Encrypt
    public RespModel getPrePayId(String orderNum, BigDecimal amount, String businessName) {
        if (StringUtils.isEmpty(orderNum) || amount == null || StringUtils.isEmpty(businessName)) {
            return new RespModel<>().getRespModelInstance(AppConstant.PARAM_IS_MISS, "参数不正确", null);
        }
        Map<String, Object> resultMap = new HashMap();
        try {
            String requestUrl = "http://192.168.254.40:8080/ytdataservice/wechatPay/getPrePayId.do";

            Map<String, Object> argsMap = new HashMap<String, Object>();
            argsMap.put("orderNum", orderNum);        //用户手机号
            argsMap.put("amount", amount);            //状态
            argsMap.put("businessName", businessName);        //页面
            String argsStr = JSONObject.toJSON(argsMap).toString();
            String output = HttpClientUtil.httpRequest(requestUrl + "?data=" + URLEncoder.encode(argsStr, "utf-8"), null);
            resultMap = (Map<String, Object>) JSONObject.parse(output);
            return new RespModel().getRespModelInstance(AppConstant.STATU_SUCCESS, "", resultMap);
        } catch (Exception e) {
            return new RespModel().getRespModelInstance(AppConstant.STATU_FAIL, "微信服务异常", null);
        }

    }

    /**
     * 微信回调
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/cgsOrderWxNotify")
    public void cgsOrderWxNotify(HttpServletRequest request, HttpServletResponse response) throws IOException {
        byte[] bytes = null;
        try (InputStream inStream = request.getInputStream();
             ByteArrayOutputStream outSteam = new ByteArrayOutputStream()) {
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inStream.read(buffer)) != -1) {
                outSteam.write(buffer, 0, len);
            }
            bytes = outSteam.toByteArray();
            System.out.println("~~~~~~~~~~~~~~~~付款成功~~~~~~~~~");
        } catch (Exception e) {
            e.printStackTrace();
        }
        // <xml>
        // <appid><![CDATA[wx2421b1c4370ec43b]]></appid>
        // <attach><![CDATA[支付测试]]></attach>
        // <bank_type><![CDATA[CFT]]></bank_type>
        // <fee_type><![CDATA[CNY]]></fee_type>
        // <is_subscribe><![CDATA[Y]]></is_subscribe>
        // <mch_id><![CDATA[10000100]]></mch_id>
        // <nonce_str><![CDATA[5d2b6c2a8db53831f7eda20af46e531c]]><nce_str>
        // <openid><![CDATA[oUpF8uMEb4qRXf22hE3X68TekukE]]></openid>
        // <out_trade_no><![CDATA[1409811653]]></out_trade_no>
        // <result_code><![CDATA[SUCCESS]]></result_code>
        // <return_code><![CDATA[SUCCESS]]></return_code>
        // <sign><![CDATA[B552ED6B279343CB493C5DD0D78AB241]]></sign>
        // <sub_mch_id><![CDATA[10000100]]></sub_mch_id>
        // <time_end><![CDATA[20140903131540]]></time_end>
        // <total_fee>1</total_fee>
        // <trade_type><![CDATA[JSAPI]]></trade_type>
        // <transaction_id><![CDATA[1004400740201409030005092168]]></transaction_id>
        // </xml>
        String result = new String(bytes, "utf-8");// 获取微信调用我们notify_url的返回信息
        System.out.println("微信调用我们notify_url的返回信息" + result);
        Map<String, Object> map = XMLMapUtil.xmlString2Map(result);
        if ("SUCCESS".equals(MapUtils.getString(map, "result_code")) && "SUCCESS".equals(MapUtils.getString(map, "return_code"))) {
            String orderNum = MapUtils.getString(map, "out_trade_no");
            String wxOrderNum = MapUtils.getString(map, "transaction_id");
            String payTime = LocalDateTime.now().toString();
            cgsBusinessService.setPostPaySuc(orderNum, wxOrderNum, payTime);
        }
    }

    /**
     * 订单查询
     *
     * @param request
     */
    @GetMapping("/orderquery")
    @ApiOperation(value = "获取订单信息")
//    @com.cxytiandi.encrypt.springboot.annotation.Decrypt
    @com.cxytiandi.encrypt.springboot.annotation.Encrypt
    public RespModel orderquery(HttpServletRequest request) {
        String orderNum = request.getParameter("orderNum");
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            String requestUrl = "http://192.168.254.40:8080/ytdataservice/wechatPay/orderquery.do";

            Map<String, Object> argsMap = new HashMap<String, Object>();
            argsMap.put("orderNum", orderNum);        //订单号
            String argsStr = JSONObject.toJSONString(argsMap);
            String output = HttpClientUtil.httpRequest(requestUrl + "?data=" + URLEncoder.encode(argsStr, "utf-8"), null);

            resultMap = (Map<String, Object>) JSONObject.parse(output);
            return new RespModel().getRespModelInstance(AppConstant.STATU_SUCCESS, "", resultMap);
        } catch (Exception e) {
            e.printStackTrace();
            return new RespModel().getRespModelInstance(AppConstant.STATU_FAIL, "", null);
        }
    }

    /**
     * 发起退款
     */
    @PostMapping(value = "/refundApply", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "发起退款", produces = MediaType.APPLICATION_JSON_VALUE)
    @com.cxytiandi.encrypt.springboot.annotation.Decrypt
    @com.cxytiandi.encrypt.springboot.annotation.Encrypt
    public RespModel refundApply(String orderNum, String totalFee, String wxOrderNum) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            String requestUrl = "http://192.168.254.40:8080/ytdataservice/wechatPay/refundApply.do";

            Map<String, Object> argsMap = new HashMap<String, Object>();
            argsMap.put("orderNum", orderNum);        //订单号
            argsMap.put("totalFee", totalFee);        //总金额
            argsMap.put("notifyUrl", "http://222.174.70.56:18082/dataservice/api/cgsOrder/refundNotify.do");    //回调地址
            String argsStr = JSONObject.toJSONString(argsMap);
            String output = HttpClientUtil.httpRequest(requestUrl + "?data=" + URLEncoder.encode(argsStr, "utf-8"), null);

            JSONObject resObj = JSONObject.parseObject(output);
            String code = resObj.getString("code");
            if ("1".equals(code)) {
                Map<String, Object> refundMap = resObj.getObject("refundApplyRes", HashMap.class);
                String result_code = MapUtils.getString(refundMap, "result_code");
                String return_code = MapUtils.getString(refundMap, "return_code");
                //修改状态
                if ("SUCCESS".equals(return_code) && "SUCCESS".equals(result_code)) {
                    return new RespModel<>().getRespModelInstance(AppConstant.STATU_SUCCESS, "退款申请成功", null);
                } else {
                    return new RespModel().getRespModelInstance(AppConstant.STATU_FAIL, MapUtils.getString(refundMap, "err_code_desc"), null);
                }
            } else {
                return new RespModel().getRespModelInstance(AppConstant.STATU_FAIL, "微信服务异常", null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new RespModel().getRespModelInstance(AppConstant.STATU_FAIL, "微信服务异常", null);
        }
    }

    /**
     * 退款结果通知（退款回调）
     *
     * @param request
     * @param response
     */
    @RequestMapping("/refundNotify")
    public void refundNotify(HttpServletRequest request, HttpServletResponse response) {
        try (InputStream inStream = request.getInputStream();
             ByteArrayOutputStream outSteam = new ByteArrayOutputStream()) {
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inStream.read(buffer)) != -1) {
                outSteam.write(buffer, 0, len);
            }
            System.out.println("~~~~~~~~~~~~~~~~退款成功~~~~~~~~~");
//			<xml>
//			<return_code>SUCCESS</return_code>
//			   <appid><![CDATA[wx2421b1c4370ec43b]]></appid>
//			   <mch_id><![CDATA[10000100]]></mch_id>
//			   <nonce_str><![CDATA[TeqClE3i0mvn3DrK]]></nonce_str>
//			   <req_info><![CDATA[T87GAHG17TGAHG1TGHAHAHA1Y1CIOA9UGJH1GAHV871HAGAGQYQQPOOJMXNBCXBVNMNMAJAA]]></req_info>
//			</xml>

            String result = new String(outSteam.toByteArray(), "utf-8");// 获取微信调用我们notify_url的返回信息
            System.out.println("微信调用我们notify_url的返回信息" + result);

            Map<String, Object> map = XMLMapUtil.xmlString2Map(result);
            String reqInfo = MapUtils.getString(map, "req_info");
//            cgsBusinessService.setPostPayTk(orderNum, wxOrderNum, LocalDateTime.now().toString());
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 查询退款
     *
     * @param request
     * @param response
     */
    @SuppressWarnings("unchecked")
    @GetMapping(value = "/refundquery", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "查询退款")
//    @com.cxytiandi.encrypt.springboot.annotation.Decrypt
    @com.cxytiandi.encrypt.springboot.annotation.Encrypt
    public RespModel refundquery(HttpServletRequest request, HttpServletResponse response) {
        String orderNum = request.getParameter("orderNum");
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            String requestUrl = "http://192.168.254.40:8080/ytdataservice/wechatPay/refundApply.do";

            Map<String, Object> argsMap = new HashMap<String, Object>();
            argsMap.put("orderNum", orderNum);        //订单号
            String argsStr = JSONObject.toJSONString(argsMap);
            String output = HttpClientUtil.httpRequest(requestUrl + "?data=" + URLEncoder.encode(argsStr, "utf-8"), null);

            resultMap = (Map<String, Object>) JSONObject.parse(output);
            Map<String, Object> refundResMap = JSON.parseObject("refundRes", HashMap.class);

            String refundStatus = MapUtils.getString(refundResMap, "refundStatus");
            String refundSccessTime = MapUtils.getString(refundResMap, "refundSuccessTime");
//            if("SUCCESS".equals(refundStatus)){
//                this.cgsBusinessService.updateOrderRefundStatus(orderNum,refundSccessTime);
//            }

            resultMap.put("refundRes", refundResMap);
            return new RespModel().getRespModelInstance(AppConstant.STATU_SUCCESS, "", resultMap);
        } catch (Exception e) {
            e.printStackTrace();
            return new RespModel().getRespModelInstance(AppConstant.STATU_FAIL, "查询异常", null);
        }
    }

    /**
     * 保存民意诉求咨询问题
     */
    @Login
    @PostMapping(value = "/saveCgsQuestion/{applicationId}", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "提交民意咨询")
    @com.cxytiandi.encrypt.springboot.annotation.Decrypt
    @com.cxytiandi.encrypt.springboot.annotation.Encrypt
    public RespModel saveCgsQuestion(@Valid CgsQuestion cgsQuestion, BindingResult bindingResult, HttpServletRequest request) {
        List<String> strings = customizeCheckFieldAdapter(bindingResult);
        if (!CollectionUtils.isEmpty(strings)) {
            return new RespModel().getRespModelInstance(AppConstant.PARAM_IS_MISS, StringUtils.join(strings, ","), null);
        }
        String userId = (String) request.getAttribute("username");
        Map map = personalCenterService.queryAppUserInfo(userId);
        if (CollectionUtils.isEmpty(map)) {
            return new RespModel().getRespModelInstance(AppConstant.CONDITION_NOT_SATISFIED, "请先升级为VIP", null);
        }
        try {
            if (StringUtils.isNotEmpty(cgsQuestion.getQuestionImg()) && cgsQuestion.getQuestionImg().indexOf("data:image") >-1) {
                String questionImg = uploadBase64StrImage(cgsQuestion.getQuestionImg(), userId + "-Question.png");
                cgsQuestion.setQuestionImg(questionImg);
            }
            cgsQuestion.setId(UUIDGenerator.getUUID());
            cgsQuestion.setApplyUserId(userId);
            cgsQuestion.setApplyUserName(((String) map.get("real_name")));
            cgsQuestion.setIdCardNum(((String) map.get("sfzh")));
            Integer res = cgsBusinessService.insertCgsQuestion(cgsQuestion);

            if (res == null || res != 1) {
                return new RespModel().getRespModelInstance(AppConstant.STATU_FAIL, "提交失败", null);
            } else {
                return new RespModel().getRespModelInstance(AppConstant.STATU_SUCCESS, "", null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new RespModel().getRespModelInstance(AppConstant.STATU_FAIL, "", null);
        }
    }

    @GetMapping(value = "/getMyQuestionList/{userId}", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "查询我的民意咨询")
//    @com.cxytiandi.encrypt.springboot.annotation.Decrypt
    @com.cxytiandi.encrypt.springboot.annotation.Encrypt
    public RespModel getMyCgsQuestionList(@PathVariable String userId) {
        if (StringUtils.isEmpty(userId)) {
            return new RespModel<>().getRespModelInstance(AppConstant.PARAM_IS_MISS, "用户标识缺失", null);
        }
        List<Map> dataMap = this.cgsBusinessService.getMyQuestionList(userId);
        return new RespModel().getRespModelInstance(AppConstant.STATU_SUCCESS, "", dataMap);
    }

    @GetMapping(value = "/getHotQuestionList", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "热门民意列表", produces = MediaType.APPLICATION_JSON_VALUE)
//    @com.cxytiandi.encrypt.springboot.annotation.Decrypt
    @com.cxytiandi.encrypt.springboot.annotation.Encrypt
    public RespModel getHotQuestionList(HttpServletRequest request) {
        String pageNoStr = request.getParameter("pageNo");
        String pageSizeStr = request.getParameter("pageSize");

        int pageNo = StringUtils.isBlank(pageNoStr) ? 1 : Integer.valueOf(pageNoStr);
        int pageSize = StringUtils.isBlank(pageSizeStr) ? 10 : Integer.valueOf(pageSizeStr);
        Map hotQuestionList = this.cgsBusinessService.getHotQuestionList(pageNo, pageSize);
        return new RespModel<>().getRespModelInstance(AppConstant.STATU_SUCCESS, "", hotQuestionList);
    }

    @Login
    @PostMapping(value = "/saveCgsAppeal/{applicationId}", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "保存民意诉求", produces = MediaType.APPLICATION_JSON_VALUE)
    @com.cxytiandi.encrypt.springboot.annotation.Decrypt
    @com.cxytiandi.encrypt.springboot.annotation.Encrypt
    public RespModel saveCgsAppeal(@Valid CgsAppeal cgsAppeal, BindingResult bindingResult, HttpServletRequest request) {
        List<String> strings = customizeCheckFieldAdapter(bindingResult);
        if (!CollectionUtils.isEmpty(strings)) {
            return new RespModel().getRespModelInstance(AppConstant.PARAM_IS_MISS, StringUtils.join(strings, ","), null);
        }

        String userId = (String) request.getAttribute("username");
        Map map = personalCenterService.queryAppUserInfo(userId);
        if (CollectionUtils.isEmpty(map)) {
            return new RespModel().getRespModelInstance(AppConstant.CONDITION_NOT_SATISFIED, "请先升级为VIP", null);
        }
        cgsAppeal.setApplyUserId(userId);
        cgsAppeal.setApplyUserName(MapUtils.getString(map, "real_name"));
        cgsAppeal.setIdCardNum(MapUtils.getString(map, "sfzh"));
        cgsAppeal.setId(UUID.randomUUID().toString());
        if (StringUtils.isNotEmpty(cgsAppeal.getAppealImg())) {
            String appealImg = uploadBase64StrImage(cgsAppeal.getAppealImg(), userId + "-AppealImage.png");
            cgsAppeal.setAppealImg(appealImg);
        }

        Integer insert_count = cgsBusinessService.insertCgsAppeal(cgsAppeal);
        if (insert_count == null || insert_count != 1) {
            return new RespModel().getRespModelInstance(AppConstant.STATU_FAIL, "提交失败", null);
        }

        return new RespModel().getRespModelInstance(AppConstant.STATU_SUCCESS, "", null);
    }
    @Login
    @GetMapping(value = "/getMyCgsAppealList/{applicationId}", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "查询我的民意诉求", produces = MediaType.APPLICATION_JSON_VALUE)
//    @com.cxytiandi.encrypt.springboot.annotation.Decrypt
    @com.cxytiandi.encrypt.springboot.annotation.Encrypt
    public RespModel getMyCgsAppealList(HttpServletRequest request) {
        String userId = (String) request.getAttribute("username");
        List<CgsAppeal> myCgsAppealList = this.cgsBusinessService.getMyCgsAppealList(userId);
        return new RespModel().getRespModelInstance(AppConstant.STATU_SUCCESS, "", myCgsAppealList);
    }
}
